package mymyoux.data
{
	import flash.net.SharedObject;
	
	import mymyoux.utils.Hash;
	
	import org.osflash.signals.Signal;
	/**
	 * Manages cache data
	 */
	public class Cache
	{
		/**
		 * @private
		 */
		private var _varChanged:Signal;
		/**
		 * @private
		 */
		private var _name:String;
		/**
		 * @private
		 */
		private var _nameChanged:Signal;
		/**
		 * Contains all registered vars
		 */
		private var _vars:Hash;
		private var _cache:SharedObject;
		/**
		 * Creates an instance of Cache class
		 * @param name Name used by the SharedObject.getLocal() function
		 */
		public function Cache(name:String)
		{
			_varChanged = new Signal();
			_nameChanged = new Signal(String);
			_vars = new Hash();
			_name = name;
			loadVars();
		}
		/**
		 * Signal dispatched when the name of the SharedObject has changed
		 */
		public function get nameChanged():Signal
		{
			return _nameChanged;
		}
		/**
		 * Signal dispatched when a var is modified
		 */
		public function get varChanged():Signal
		{
			return _varChanged;
		}
		/**
		 * Name of the SharedObject
		 */
		public function get name():String
		{
			return _name;
		}
		public function set name(name:String):void{
			_name = name;
			_nameChanged.dispatch(name);
			loadVars();
		} 
		
		/**
		 * Var linked to the given name
		 * @param name Name
		 * @return SharedVar linked to the name
		 */
		public function get(name:String):CachedVar
		{
			if(!_vars.exists(name))
			{
				_vars.put(name,new CachedVar(name,this));	
			}
			return _vars.get(name) as CachedVar;
		}
		//TODO:faire en sorte que ça marche même au début!!
		/**
		 * Indicates if the var is indexed.
		 * @return true or false.
		 */
		public function contains(name:String):Boolean
		{
			return _vars.exists(name) && _vars.get(name).value!=null;
		}
		/**
		 * Return an array with all names of indexed vars.
		 * @return Array with all names of indexed vars.
		 */
		public function getArray():Array{
			return _vars.keys;
		}
		private function loadVars():void
		{
			_cache = SharedObject.getLocal(name);
			var p:String;
			
			//var oldKeys:Array = _vars.keys;
				
			//var index:int;
			for(p in _cache.data)
			{		/*		
				if((index = oldKeys.indexOf(p)) > -1)
				{
					oldKeys.splice(index, 1);
				}*/
				get(p).value = _cache.data[p];
			}
		}
	}
}